package cn.sczhyt.modules.szhy.service.impl;

import cn.sczhyt.common.exception.RRException;
import cn.sczhyt.common.utils.DownloadFileUtils;
import cn.sczhyt.common.utils.R;
import cn.sczhyt.modules.szhy.entity.MeetingFileEntity;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.sczhyt.common.utils.PageUtils;
import cn.sczhyt.common.utils.Query;

import cn.sczhyt.modules.szhy.dao.MeetingMobileAppDao;
import cn.sczhyt.modules.szhy.entity.MeetingMobileAppEntity;
import cn.sczhyt.modules.szhy.service.MeetingMobileAppService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Service("meetingMobileAppService")
public class MeetingMobileAppServiceImpl extends ServiceImpl<MeetingMobileAppDao, MeetingMobileAppEntity> implements MeetingMobileAppService {


    /**
     * 文件配置
     */
    @Value("${cn.sczhyt.szhy.apk.upload-path}")
    private  String apkPath;

    /**
     * 文件配置
     */
    @Value("${cn.sczhyt.szhy.apk.package-name}")
    private  String packageName;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MeetingMobileAppEntity> page = this.page(
                new Query<MeetingMobileAppEntity>().getPage(params),
                new QueryWrapper<MeetingMobileAppEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void download(String appId, HttpServletResponse response, HttpServletRequest request) {
        MeetingMobileAppEntity mobileAppEntity = baseMapper.selectById(appId);
        //真实路径/opt/zhyt-szhy/apk
        //实际路径 http://118.24.254.66:8003/apk/
        String[] split = mobileAppEntity.getRealPath().split("/apk/");
        String path = split[1];
        System.out.println(path);
        File file = new File(apkPath + path);
        try {
            DownloadFileUtils.downloadFile(mobileAppEntity.getPackageName(), file, response, request);
        } catch (UnsupportedEncodingException e) {
            throw new RRException("文件下载出错",201);
        }
    }

    @Override
    public R getReleaseLatestApk() {
        QueryWrapper<MeetingMobileAppEntity> queryWrapper = new QueryWrapper<MeetingMobileAppEntity>()
                .eq("package_name", packageName)
                .eq("status",true)
                .orderByDesc("version_code");
        List<MeetingMobileAppEntity> list = this.list(queryWrapper);

        if (list.isEmpty()) {

            return R.error(2001,"没有有效的APK包!");
        }

        String url = list.get(0).getRealPath();

        return R.ok().put("data",url);
    }

    @Override
    public R upgradeInfo(String versionCode,HttpServletRequest request, HttpServletResponse response) {

        QueryWrapper<MeetingMobileAppEntity> queryWrapper = new QueryWrapper<MeetingMobileAppEntity>()
                .eq("package_name", packageName)
                .eq("status",true)
                .gt("version_code",Integer.parseInt(versionCode))
                .orderByDesc("version_code");
        List<MeetingMobileAppEntity> apps = this.list(queryWrapper);
        //没有最新版本 直接返回
        if (apps.isEmpty()) {

            return null;
        }

        if(apps.size() == 1){
            //返回最新版本
            return R.ok().put("data",apps.get(0));
        }
        for (int i = 0; i < apps.size(); i++) {
            if (!apps.get(i).getForceUpdate()) {

                // 判断所有有效的版本，是否拥有强制更新
                if (apps.get(i+1).getForceUpdate()) {
                    //有强制更新
                       return R.ok().put("data",apps.get(i+1));
                }
            }
        }
        //返回最新版本
        return R.ok().put("data",apps.get(0));

    }

}